<template>
  <div>
    <!-- 导航提示信息 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>考试管理</el-breadcrumb-item>
      <el-breadcrumb-item>在线考试</el-breadcrumb-item>
    </el-breadcrumb>
    <br />

    <!-- 模糊查询表单 -->
    <el-row>
      <el-col :span="14">
        <template>
          <el-form :inline="true" :model="examPage" class="demo-form-inline">
            <el-form-item label="编号">
              <el-input
                v-model="examPage.examId"
                placeholder="编号"
                style="width: 140px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="试卷名">
              <el-input
                v-model="examPage.examTitle"
                placeholder="试卷名称"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadData">查询</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-col>
      <!-- <el-col>
      </el-col> -->
    </el-row>

    <!-- 表格数据展示 -->
    <template>
      <el-table :data="examList" style="width: 100%" max-height="350">
        <el-table-column fixed="left" label="编号" width="100">
          <template slot-scope="x">
            <span style="margin-left: 10px">{{ x.row.examId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="试卷名" width="260">
          <template slot-scope="x">
            <span>{{ x.row.examTitle }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="280">
          <template slot-scope="x">
            <span>{{ x.row.examCreatetime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="满分" width="230">
          <template slot-scope="x">
            <span>{{ x.row.examFullscore }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="140">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="joinExam(scope.$index, scope.row)"
            >
              在线考试
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <!-- <span class="demonstration">完整功能</span> -->
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="examPage.page"
          :page-sizes="[2, 3, 5]"
          :page-size="examPage.row"
          layout="total, sizes, prev, pager, next, jumper"
          :total="examPage.total"
        >
        </el-pagination>
      </div>
    </template>

    <!-- <template>
      <div>
        <button type="button" @click="openVideo('showVideo')">打开摄像头</button>
        <button type="button" @click="closeVideo('showVideo')">关闭摄像头</button>
      </div>
    </template> -->

    <template>
      <!-- 在线考试模态框 -->
      <el-dialog
        title="在线考试"
        :visible="onexamVisible"
        :before-close="closeWin"
        width="80%"
        @opened="openVideo()"
        :fullscreen="true"
      >
        <div style="display: flex">
          <!-- 考题信息 -->
          <div class="examInfo">
            <el-form ref="examForm" :rules="rules" label-width="100px">
              <div v-for="(item, index) in onExamList" :key="index">
                <el-form-item>
                  <span v-if="item.questionType == '单选题'"
                    >{{ index + 1 }}&nbsp;. (单选题) {{ item.questionTopic }}
                    <br />
                    <el-radio-group
                      v-model="item.stuAnswer"
                      @change="
                        (val) => changeSingleChoice(val, item.questionId)
                      "
                    >
                      <el-radio label="A">A. {{ item.questionA }}</el-radio>
                      <br />

                      <el-radio label="B">B. {{ item.questionB }}</el-radio>
                      <br />

                      <el-radio label="C">C. {{ item.questionC }}</el-radio>
                      <br />

                      <el-radio label="D">D. {{ item.questionD }}</el-radio>
                    </el-radio-group>
                  </span>
                  <span v-else-if="item.questionType == '判断题'"
                    >{{ index + 1 }}&nbsp;. (判断题) {{ item.questionTopic }}
                    <br />
                    <el-radio-group
                      v-model="item.stuAnswer"
                      @change="(val) => changeJudge(val, item.questionId)"
                    >
                      <el-radio border size="small" label="√">√</el-radio>
                      <!-- <br/> -->
                      <el-radio border size="small" label="×">×</el-radio>
                    </el-radio-group>
                  </span>
                </el-form-item>
              </div>

              <!-- 提交试卷 -->
              <el-form-item>
                <el-row>
                  <el-button
                    type="success"
                    round
                    size="medium"
                    @click="saveSubmit('examForm')"
                    >提交</el-button
                  >
                </el-row>
              </el-form-item>
            </el-form>
          </div>
          <div class="tips">
            <!-- 考试倒计时 -->
            <div class="timeTip">
              <span>距离考试结束还有:</span><span id="dddd">00:15:00</span>
            </div>
            <!-- 摄像头显示区域 -->
            <div id="showVideo"></div>
          </div>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
// 导入摄像头工具类
import faceUtil from "../util/faceUtil.js";
// 导入 请求统一的URL
import myUtil from "../util/MyUtil.js";

export default {
  methods: {
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
  },
  data() {
    return {
      rules: {
        singleChoice: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        judge: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
      tableData: [],
      examList: [], // 试卷列表
      examPage: {
        // 试卷分页
        page: 1,
        row: 3,
        total: 0,
        examId: null, // id查询
        examTitle: "", // 试卷名称查询
      },
      examPaper: {
        // 试卷对象
        examId: 0,
        examTitle: " ",
        examCreateTime: "",
        examFullscore: 0,
        subjectId: null,
        examList: [],
      },
      onexamVisible: false, // 在线考试模态框
      onExamList: [],
      // 考生答案
      answerList: [],
      // 试卷编号
      examanationId: null,
      // 答案对象
      answerSheet: {
        answerId: null,
        examId: null,
        questionId: null,
        rightAnswer: null,
        stuAnswer: null,
        questionScore: null,
        answerScore: null,
        stuId: null,
        answerList: null,
      },
    };
  },
  methods: {
    loadData() {
      var self = this;
      // console.log(JSON.stringify(self.examPage));
      $.ajax({
        url: myUtil.url + "/exampaper/list",
        type: "get",
        data: self.examPage,
        dataType: "json",
        success: function (rs) {
          // console.log(rs);
          self.examList = rs.list;
          self.examPage.total = rs.total;
          // self.$message(rs.info);
          // console.log("加载成功");
        },
        error: function (rs) {
          // console.log(rs);
          // console.log("加载失败");
        },
      });
    },
    sizeChange(val) {
      this.examPage.row = val;
      this.loadData();
    },
    currentChange(val) {
      this.examPage.page = val;
      this.loadData();
    },
    closeWin() {
      var self = this;
      self
        .$confirm("此操作将自动提交试卷, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          self.onexamVisible = false;
          // self.examanationId = 0;
          // 清空答案列表
          let size = self.answerList.length;
          self.answerList.splice(0, size);

          self.$message({
            type: "warning",
            message: "正在提交试卷",
          });
          faceUtil.closess();
          // 考生关闭窗口,
          self.answerSheet.answerList = self.answerList;
          //
          // self.answerSheet.stuId = 5;
          // 提交试卷
          $.ajax({
            url: myUtil.url + "/answerSheet/submitPaper",
            type: "post",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(self.answerSheet),
            success: function (rs) {
              // console.log("关闭");
              self.$alert(rs.score);
            },
            error: function (rs) {
              console.log("请求失败");
            },
          });
          // 清空画图区域
          // $('#' + showVideo + '').empty();
          self.examanationId = 0;
          self.answerSheet = {};
        })
        .catch(() => {
          self.$message({
            type: "success",
            message: "继续考试",
          });
        });
    },
    openVideo() {
      // 打开摄像头
      faceUtil.openVideo("showVideo");
    },
    closeVideo() {
      // window.mediaStreamTrack.stop();
      // 关闭摄像头
      faceUtil.closess();
    },
    // 加载试卷，并开始计时
    joinExam(index, row) {
      // 在线考试
      // console.log("参加考试");

      var self = this;
      self.examanationId = row.examId;
      self.answerSheet.examId = row.examId;
      self
        .$confirm(
          "此操作将进行在线考试,并且中途不能关闭窗口, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          // 提示
          self.$message({
            type: "success",
            message: "考试",
          });
          // 考生编号，用来验证当前考生是否参加过本场考试
          let stuId = self.answerSheet.stuId;
          // 加载试题
          $.ajax({
            url: myUtil.url + "/exampaper/examination",
            type: "get",
            dataType: "json",
            data: {
              examId: row.examId,
              stuId: stuId,
            },
            success: function (rs) {
              // console.log("success");
              // console.log(rs.exam.examList);
              // 判断是否参加过该场考试
              if (rs.info == "already") {
                self.$alert("你已经参与过本场考试,不能再次参加");
              } else {
                self.onExamList = rs.exam.examList;

                self.onexamVisible = true;
                // 时钟倒计时
                window.jQuery(function ($) {
                  // "use strict";
                  // console.log("111111111")
                  $("time").countDown({
                    with_separators: false,
                  });
                  $("#dddd")
                    .countDown()
                    .on("time.elapsed", function () {
                      // 时间到了提交试卷
                      self.answerSheet.answerList = self.answerList;
                      // 提交试卷
                      $.ajax({
                        url: myUtil.url + "/answerSheet/submitPaper",
                        type: "post",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(self.answerSheet),
                        success: function (rs) {
                          // console.log("关闭");
                          self.$alert(rs.score);
                        },
                        error: function (rs) {
                          console.log("请求失败");
                        },
                      });
                      // 清空画图区域
                      // $('#' + showVideo + '').empty();
                      self.examanationId = 0;
                      self.answerSheet = {};
                    });
                });
              }
            },
            error: function (rs) {
              console.log("error");
            },
          });
        })
        .catch(() => {
          self.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 倒计时
    countDown() {},
    // 单选题
    changeSingleChoice(val, questionId) {
      let self = this;
      // console.log(self.answerList.length);
      // 同一题变更答案时删除以前选择的答案
      if (self.answerList.length >= 1) {
        for (let i = 0; i < self.answerList.length; i++) {
          if (self.answerList[i].questionId == questionId) {
            self.answerList.splice(i, 1);
          }
        }
      }

      let answer = {
        examId: 0,
        questionId: "",
        stuAnswer: "",
      };
      answer.examId = self.examanationId;
      answer.questionId = questionId;
      answer.stuAnswer = val;
      // console.log("answerSheet=="+answerSheet);
      self.answerList.push(answer);
      // console.log(self.answerList);
    },
    // 判断题
    changeJudge(val, questionId) {
      let self = this;
      // 同一题变更答案时删除以前选择的答案
      if (self.answerList.length >= 1) {
        for (let i = 0; i < self.answerList.length; i++) {
          if (self.answerList[i].questionId == questionId) {
            self.answerList.splice(i, 1);
          }
        }
      }

      let answer = {
        examId: 0,
        questionId: "",
        stuAnswer: "",
      };
      // console.log(self.examanationId);
      answer.examId = self.examanationId;
      answer.questionId = questionId;
      answer.stuAnswer = val;
      // console.log("answerSheet=="+answerSheet);
      self.answerList.push(answer);
      // console.log(self.answerList);
    },
    saveSubmit(formName) {
      // console.log("提交试卷");
      var self = this;

      self.answerSheet.answerList = self.answerList;
      // self.answerSheet.stuId = 5;

      self
        .$confirm("此操作将提交试卷, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          $.ajax({
            url: myUtil.url + "/answerSheet/submitPaper",
            type: "post",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(self.answerSheet),
            success: function (rs) {
              // console.log(rs.score);
              // 清空答案列表
              self.answerList.splice(0, self.answerList.length);
              // 给出当前考生的成绩得分
              self.$alert(rs.score, "成绩", {
                confirmButtonText: "确定",
                callback: (action) => {
                  // 关闭摄像头
                  faceUtil.closess();
                  // 关闭模态框
                  self.onexamVisible = false;
                  // 清空试卷编号
                  self.examanationId = 0;
                  // 清空答案对象
                  self.answerSheet = {};
                },
              });
            },
            error: function (rs) {
              console.log("请求失败");
            },
          });
        })
        .catch(() => {
          self.$message({
            type: "success",
            message: "继续考试",
          });
        });
    },
  },
  mounted() {
    this.loadData();
    let studentId = localStorage.getItem("studentId");
    this.answerSheet.stuId = studentId;
  },
};
</script>

<style>
/* #myVideo {
  margin-top: -40px;
    margin-left: 816px;
    position: fixed; 
    margin-left: 85%; 
}*/

.timeTip {
  margin-right: 25%;
  font-size: 17px;
  /* color: #ca123a; */
  /* display: inline-block; */
  vertical-align: middle;
  /* width: 120px; */
}

#dddd {
  color: #ca123a;
}

#showVideo {
  /* display: inline-block; */
  margin-left: 11%;
}

.tips {
  width: 500px;
  height: 300px;
  margin-left: 20%;
}

.examInfo {
  width: 95%;
}

.el-radio {
  margin-top: 6px;
  /* margin-bottom: 2px; */
}
</style>
